<template>
  <div>
    <FlowApproveEditor @showHistory="showHistory"
      @flowModelChange="flowModelChange" ref="refFlowApproveEditor"/>
    <TaskHistoryInfo ref="refTaskHistoryInfo"/>
  </div>
</template>
<script setup>
import {shallowRef} from 'vue';
import {getAction} from '@/request/BaseRequest';
import TaskHistoryInfo from '@/components/platwork/FlowModelWithHistory/TaskHistoryInfo.vue';
import FlowApproveEditor from './FlowApproveEditor';

defineOptions({
  name: 'FlowApproveEditorComponent'
});

const refFlowApproveEditor = shallowRef();
const refTaskHistoryInfo = shallowRef();
let processInstanceId = undefined;
const emits = defineEmits(['flowModelChange']);
const props = defineProps({
  formDefinition: {
    form: {},
    formFields: []
  }
});

function setData(_processInstanceId) {
  processInstanceId = _processInstanceId;

  getAction('/flow/loadProcessHistoryByProcessInstanceId',
    {processInstanceId}).then(data => {
    if (data.success) {
      let result = data.result;

      setProcessHistory(result);
    }
  });
}

function setProcessHistory(flowImageHistory) {
  flowImageHistory.flowModel = JSON.parse(flowImageHistory.flowDefinition);

  props.formDefinition.form.viewActions = [props.formDefinition.form.viewAction]
  getAction('/plat/loadViewsAndViewActionsByPublishId', {formId: props.formDefinition.form.id}).then(data => {
    if (data.success) {
      let result = data.result;
      props.formDefinition.form.viewActions = result.viewActions
      props.formDefinition.form.views = result.views
      refFlowApproveEditor.value.setFormDefinition(props.formDefinition.form);
      refFlowApproveEditor.value.setData(flowImageHistory.flowModel);
      refFlowApproveEditor.value.setFlowImageHistory(flowImageHistory);
    }
  })

}

function flowModelChange(flowModel, before) {
  emits('flowModelChange', flowModel, before);
}

function showHistory(element) {
  refTaskHistoryInfo.value.setData(element, processInstanceId);
}

defineExpose({
  setData
});
</script>
